<template>
    <div class="search">
        <input type="text" placeholder="请输入要查询的城市" v-model="keyWords">
        <div class="search-content" v-show="show" ref="wrapper">
            <div>
                <div class="item border-bottom" v-for="item in data.resultList" :key="item.id"
                @click="change(item.name)">
                {{item.name}}
                </div>
                <div class="tip" v-show="!showMessage">没有查询到结果</div>
            </div>
        </div>
    </div>
</template>
<script>
import BScroll from 'better-scroll'
import { reactive, ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoter } from 'vue-router'
export default {
  name: 'CitySearch',
  props: {
    cities: {
      type: Object
    },
    alphabet: {
      type: Array
    }
  },
  setup(props){
    let data = reactive({
      resultList: []
    })
    let keyWords = ref('')
    let timer = null
    // let store = useStore()
    // let router = useRoter()
    // let wrapper = ref(null)
    let show = computed(()=>{
      return keyWords.value
    })
    let showMessage = computed(()=>{
      return data.resultList.length
    })
    watch(keyWords, (newVal, oldVal)=>{
      //newVale === kewWords.value
      if(newVal === ''){
        data.resultList = []
        return
      }
      if(timer){
        clearTimeout(timer)
        timer = null
      }
      timer = setTimeout(()=>{
        data.resultList = []
        props.alphabet.forEach((item)=>{
          props.cities[item].forEach((i)=>{
            if(i.spell.indexOf(newVal) !== -1){
              data.resultList.push(i)
            }
            if(i.name.indexOf(newVal) !== -1){
              data.resultList.push(i)
            }
          })
        })
      }, 8)
    })
    return { keyWords, data, show, showMessage }
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl'
    .search
        height .72rem
        padding 0 .1rem
        background-color $bgColor
        input
            width 100%
            height .62rem
            border-radius .06rem
            color #666
            box-sizing border-box
            margin-top .05rem
            text-align center
            padding 0 .1rem
        .search-content
            height 100%
            overflow hidden
            background-color #fff
            position fixed
            top 1.58rem
            left 0
            right 0
            bottom 0
            z-index 1
            .item
                line-height .62rem
                height .62rem
                color #666
                padding-left .2rem
</style>
